package org.example.codesandbox.Controller;

import cn.hutool.core.util.ObjectUtil;
import org.example.codesandbox.JavaNativeCodeSanBox;
import org.example.codesandbox.model.ExecuteCodeRequest;
import org.example.codesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/")
public class MainController {
    @Resource
    JavaNativeCodeSanBox javaNativeCodeSanBox;

    //定义鉴权请求头与密钥
    private static final String AUTH_REQUEST_HEADER = "Auth";
    private static final String AUTH_REQUEST_SECRET = "123456";

    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        String header = httpServletRequest.getHeader(AUTH_REQUEST_HEADER);
        if(!AUTH_REQUEST_SECRET.equals(header)){
            httpServletResponse.setStatus(403);
            return null;
        }
        if (ObjectUtil.isEmpty(executeCodeRequest)) {
            throw new RuntimeException("请求参数为空");
        }
        return javaNativeCodeSanBox.executeCode(executeCodeRequest);
    }
}
